<?php

namespace app\index\controller;

use app\index\model\Collect;
use app\index\model\Goods;
use app\index\model\Pictures;
use think\Controller;
use think\Db;

class CollectCtl extends Controller
{
    /*
     * 收藏商品
     */
    public function doCollect()
    {
        $gid = input('gid');
        Collect::create([
            'uid' => input('uid'),
            'gid' => $gid,
            'collect_time' => time()
        ]);
        // 相应的商品收藏数 +1
        Db::table('goods')->where('id', $gid)->setInc('collect');
        return json(['msg' => "收藏成功！", 'code' => 20000]);
    }

    /*
     * 取消收藏
     */
    public function unFavorite()
    {
        Collect::destroy(function ($query) {
            $query->where(['uid' => input('uid'), 'gid' => input('gid')]);
        });
        // 相应的商品收藏数 -1
        Db::table('goods')->where('id', input('gid'))->setDec('collect');
        return json(['msg' => "取消成功！", 'code' => 20000]);
    }

    /*
     * 获取用户的商品收藏
     */
    public function getCollectByUid()
    {
        // 查出该用户收藏的所有商品对应的id
        $collects = Collect::where('uid', input('uid'))->column('gid');
        $res = [];
        foreach ($collects as $c) {
            // 找出对应的商品信息，再加上预览图
            $goods = Goods::get($c);
            $goods['picture'] = Pictures::where(['gid' => $goods['id'], 'type' => 0])->value('url');
            $res['data'][] = $goods;
        }
        $res['code'] = 20000;
        return json($res);
    }
}